package com.relax.mybatis.plugin.sensitive.interceptor;

import java.sql.Connection;
import java.util.Properties;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;

import com.relax.mybatis.plugin.sensitive.config.SensitiveProperties;
import com.relax.mybatis.plugin.sensitive.util.SensitiveUtil;

/**
 * @author hebin
 * @date 2022/07/05
 * @desc 脱敏写拦截器
 */
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class SensitiveWriteInterceptor implements Interceptor {

    private SensitiveProperties sensitiveProperties;

    public SensitiveWriteInterceptor(SensitiveProperties sensitiveProperties) {
        this.sensitiveProperties = sensitiveProperties;
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        return SensitiveUtil.handleStatementHandler(invocation, (metaObject, fieldCacheProperty) -> SensitiveUtil
                .doSensitive(this.sensitiveProperties, metaObject, fieldCacheProperty, true));
    }

    @Override
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // do nothing
    }
}
